package model.commands.controlflow;

import java.util.Map;
import java.util.Scanner;
import model.Environment;
import model.Interpreter;
import model.SyntaxErrorException;
import model.commands.Command;


/**
 * Name:
 * FOR [ variable start end increment ] [ command(s) ]
 * 
 * Description:
 * runs the commands for each value specified in the range, i.e., from start up
 * to end, going by increment.
 * note, variable is assigned to each succeeding value so that it can be
 * accessed by the commands
 * 
 * @author Erick Gonzalez
 */
public class ForCommand extends Command {
    private Interpreter myInterpreter;
    private Map<String, Integer> myVariables;
    private String myCommandString;
    private String myVariable;
    private int myStart;
    private int myEnd;
    private int myIncrement;

    /**
     * 
     * @param interpreter an interpreter
     * @param variables variables in the current scope
     * @param commandString the for loop body
     * @param variable the for loop index
     * @param start the starting index
     * @param end the ending index
     * @param increment the for loop increment
     */
    public ForCommand(Interpreter interpreter,
                      Map<String, Integer> variables,
                      String commandString,
                      String variable,
                      int start,
                      int end,
                      int increment) {
        myInterpreter = interpreter;
        myVariables = variables;
        myCommandString = commandString;        
        myVariable = variable;
        myStart = start;
        myEnd = end;
        myIncrement = increment;
    }

    @Override
    public int evaluate(Environment e) throws SyntaxErrorException {
        int returnValue = 0;

        for (int i = myStart; i < myEnd; i += myIncrement) {
            myVariables.put(myVariable, i);
            returnValue =
                    myInterpreter.parse(new Scanner(myCommandString), myVariables).evaluate(e);
        }
        return returnValue;
    }

}
